﻿using Liju.Common;
using System;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace LiJu
{
    public partial class SignIn : Form
    {
        private Timer autoCloseTimer = null;

        private readonly string UserText = "请输入用户名";

        public string userid;

        public string username;

        public string password;

        public SignIn()
        {
            InitializeComponent();

            // 加载时启用默认双缓冲并提供无闪烁的图形呈现：
            this.DoubleBuffered = true;//设置本窗体
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲

            this.AcceptButton = BtnLogin;

            ////Lostfocus当一个控件失去焦点时触发,定义控件失去焦点时的方法
            //this.TbxUser.LostFocus += new System.EventHandler(this.TbxUser_LostFocus);
            ////GotFocus是在一个对象得到焦点时发生，定义控件得到焦点时的方法
            //this.TbxUser.GotFocus += new System.EventHandler(this.TbxUser_GotFocus);

            this.TbxUser.AutoSize = false;
            this.TbxUser.Width = 300;
            this.TbxUser.Height = 40;

            this.TbxPwd.AutoSize = false;
            this.TbxPwd.Width = 300;
            this.TbxPwd.Height = 40;

            pMESst.Location = new Point(393, 307);

            //如果前面勾选了记住密码
            //string state = ConfigurationManager.AppSettings["CheckState"];
            //if (state == "1")
            //{
            //cbUseMes.Checked = true;

            //TbxUser.Text = ConfigurationManager.AppSettings["UserID"];
            //TbxPwd.Text = EncryptionHelper.Decrypt(ConfigurationManager.AppSettings["UserPwd"]);
            //}

            //autoCloseTimer = new Timer();
            //autoCloseTimer.Interval = 1000; // 设置定时器间隔为2秒
            //autoCloseTimer.Tick += new EventHandler(AutoCloseTimer_Tick);
        }

        /// <summary>
        /// 防止闪屏
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        private void AutoCloseTimer_Tick(object sender, EventArgs e)
        {
            autoCloseTimer.Stop(); // 停止计时
                                   // 弹窗自动关闭的逻辑
                                   // 例如关闭弹窗所在的Form

            // 写入配置
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["UserID"].Value = userid;
            config.AppSettings.Settings["UserName"].Value = username;
            //config.AppSettings.Settings["UserPwd"].Value = CkbState.Checked == true ? password : "";
            //config.AppSettings.Settings["CheckState"].Value = cbUseMes.Checked == true ? "1" : "0";

            config.Save(ConfigurationSaveMode.Modified);

            // 强制刷新配置
            ConfigurationManager.RefreshSection("appSettings");

            //调用封装的写入日志方法
            PageDataDto.SystemLogInfoAdd("登录", "进行了系统登录");

            // 在这里添加登录成功后的逻辑
            this.Hide(); // 隐藏登录表单
            Main mainForm = new Main
            {
                UserName = username, // 设置Username属性的值
                UserID = userid
            };
            mainForm.Show(); // 显示首页表单
        }

        private void SignIn_Load(object sender, EventArgs e)
        {
            //读MES设置
            DataTable dt = BLL.Bll.GetSettingData();
            if (dt.Rows.Count > 0)
            {
                tbMesIP.Text = dt.Rows[0]["MesIP"].ToString().Trim();
                tbMesPort.Text = dt.Rows[0]["MesPort"].ToString().Trim();
                tbLine.Text = dt.Rows[0]["MesLine"].ToString().Trim();
                tbWorkStation.Text = dt.Rows[0]["MesWorkStation"].ToString().Trim();
                tbZiYuanNo.Text = dt.Rows[0]["MesZiYuanNo"].ToString().Trim();
            }
        }

        private void TbxUser_LostFocus(object sender, EventArgs e)
        {
            if (TbxUser.Text.Trim() == "")
            {
                TbxUser.Text = UserText;
                TbxUser.ForeColor = Color.Gray;
            }
        }
        private void TbxUser_GotFocus(object sender, EventArgs e)
        {
            if (TbxUser.Text.Trim() == UserText)
            {
                TbxUser.Text = "";
                TbxUser.ForeColor = Color.Black;
            }
        }

        private void BtnLogin_Click(object sender, EventArgs e)
        {
            //Liju.Common.MES.Login();
            //Liju.Common.MES.CheckWorkStation();
            //Liju.Common.MES.GetWorkStationProduct("0104628M7RA1400445");
            //Liju.Common.MES.GetWorkStationProduct("010463QJAR80100043");
            //Liju.Common.MES.CheckProductGongXu("0104628M7RA1200697");

            //double[] arrNiuLi = { 1.2, 2.3 };
            //double[] arrAngle = { 21.2, 30.6 };
            //bool[] arrOKorNG = { true, true };
            //Liju.Common.MES.WorkStationPass("01046174XR72600042", arrNiuLi, arrAngle, arrOKorNG, true);

            //double[] arrNiuLi = { 1.2, 2.3 };
            //double[] arrAngle = { 21.2, 30.6 };
            //bool[] arrOKorNG = { false, false };
            //Liju.Common.MES.WorkStationNG("01046174XR72600044", "GYXS-ZXDZYJ01", "NG原因11",
            //    arrNiuLi, arrAngle, arrOKorNG, false);

            //Liju.Common.MES.GetToolDeviceList("A966A01BZDH4260001");
            //Liju.Common.MES.GetExceptionMenu1();
            //Liju.Common.MES.GetExceptionMenu2("设备异常");
            //Liju.Common.MES.SaveExceptionInfo("A966GJ2561", "HCEF-2105300B 屏蔽环定位套筒", "工装类", "检测误报");
            //Liju.Common.MES.GetNeedConfirmRepairsList();

            //Liju.Common.MES.GetSongJianProductInfo("010461A1ER00600816");
            //Liju.Common.MES.GetSongJianReasonList("00074e8000025068");
            //Liju.Common.MES.SaveSongJianInfo("2302sw", "数采不良", "产品NG原因：测试，实际不送检",
            //    "00074e8000025068", "GYXS-ZHJCT", "0104616HRR80300258");
            //Liju.Common.MES.GetLineOrderList("2024-07-30", "2024-07-31", "D01-GYXS-L17");
            //Liju.Common.MES.GetSOPByOrder("D01-GYXS-L17");
            //Liju.Common.MES.GetToolDeviceESOP("A9602000725420230220");


            username = TbxUser.Text.Trim(); //用户名
            password = TbxPwd.Text.Trim();//密码
            Liju.Common.MES.IsUseMES = false;

            if (cbUseMes.Checked)//MES登陆
            {
                //username = "6279641114060A0710747003036B607577251466707E6D7075617D06017379626279"; //4278975 4278975
                if (!string.IsNullOrWhiteSpace(username))
                {
                    if (!string.IsNullOrWhiteSpace(password))//MES 有用户名 密码 无需解析
                    {
                        Liju.Common.MES.UserGongHao = username;
                        Liju.Common.MES.UsernPW = password;
                    }
                    else//MES 仅用户名需解析
                    {
                        string UserAndPwd = string.Empty;
                        try
                        {
                            UserAndPwd = Decrypt(username);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return;
                        }
                        string[] loginData = UserAndPwd.Split('|');
                        if (loginData.Length > 1)
                        {
                            Liju.Common.MES.UserGongHao = loginData[0].Replace("USER-", "");
                            Liju.Common.MES.UsernPW = loginData[1].Replace("PWD-", "");
                        }
                        else//无需解析 要验证用户名 密码
                        {
                            if (string.IsNullOrWhiteSpace(password))
                            {
                                MessageBox.Show("请输入密码！", "密码不能为空 ！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                            Liju.Common.MES.UserGongHao = username;
                            Liju.Common.MES.UsernPW = password;
                        }
                        if (string.IsNullOrWhiteSpace(Liju.Common.MES.UsernPW))
                        {
                            MessageBox.Show("账号未解析到密码，验证失败。", "账号解析错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    Liju.Common.MES.MesIP = tbMesIP.Text.Trim();
                    Liju.Common.MES.MesPort = tbMesPort.Text.Trim();
                    Liju.Common.MES.Line = tbLine.Text.Trim();
                    Liju.Common.MES.WorkStation = tbWorkStation.Text.Trim();
                    Liju.Common.MES.ZiYuanNo = tbZiYuanNo.Text.Trim();

                    MESRetrun oMESRetrun = new MESRetrun();
                    oMESRetrun = Liju.Common.MES.Login();
                    if (oMESRetrun.InterfaceJudgment)//验证成功
                    {
                        oMESRetrun = Liju.Common.MES.CheckWorkStation();
                        if (!oMESRetrun.InterfaceJudgment)
                        {
                            if (oMESRetrun.ErrInfo.Contains("MES网络或服务异常"))
                            {
                                MessageBox.Show("错误代码:E01," + oMESRetrun.ErrInfo, "MES网络或服务异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                TbxUser.Text = "";
                                TbxPwd.Text = "";
                                TbxUser.Focus();
                                MessageBox.Show(oMESRetrun.ErrInfo, "工站资源验证失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            return;
                        }

                        Liju.Common.MES.MesCheckPass = true;
                        userid = username = Liju.Common.MES.UserGongHao;

                        // 写入配置
                        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        config.AppSettings.Settings["UserID"].Value = userid;
                        config.AppSettings.Settings["UserName"].Value = username;
                        //config.AppSettings.Settings["UserPwd"].Value = CkbState.Checked == true ? password : "";
                        //config.AppSettings.Settings["CheckState"].Value = cbUseMes.Checked == true ? "1" : "0";
                        config.AppSettings.Settings["IsMesUserLogin"].Value = "1";

                        config.Save(ConfigurationSaveMode.Modified);

                        // 强制刷新配置
                        ConfigurationManager.RefreshSection("appSettings");

                        //调用封装的写入日志方法
                        PageDataDto.SystemLogInfoAdd("登录", "进行了系统登录");

                        Liju.Common.MES.IsUseMES = true;//启用MES

                        // 在这里添加登录成功后的逻辑
                        this.Hide(); // 隐藏登录表单
                        Main mainForm = new Main
                        {
                            UserName = username, // 设置Username属性的值
                            UserID = userid
                        };
                        mainForm.Show(); // 显示首页表单
                    }
                    else
                    {
                        if (oMESRetrun.ErrInfo.Contains("MES网络或服务异常"))
                        {
                            MessageBox.Show("错误代码:E01," + oMESRetrun.ErrInfo, "MES网络或服务异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            TbxUser.Text = "";
                            TbxPwd.Text = "";
                            TbxUser.Focus();
                        }
                        MessageBox.Show(oMESRetrun.ErrInfo, "账号验证失败，请重新登录。", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("请输入账号！", "账号不能为空 ！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    TbxUser.Focus();
                }
            }
            else if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
            {
                try
                {
                    password = EncryptionHelper.Encrypt(password);

                    //执行sql，验证密码等数据是否正常
                    var result = PageDataDto.SystemParentMenuRoleInfo(username, password);
                    if (result.Id > 0)
                    {
                        //如账号密码正确，判断用户状态是否正常
                        if (result.State && result.RoleCount > 0 && result.RoleState)
                        {
                            userid = result.UserID;
                            username = result.UserName;

                            //MessageBox.Show("登录成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            //autoCloseTimer.Start(); // 开始计时
                            //MessageBox.Show("登录成功！正在进入系统...", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            //autoCloseTimer.Stop(); // 停止计时
                            // 弹窗自动关闭的逻辑
                            // 例如关闭弹窗所在的Form

                            // 写入配置
                            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                            config.AppSettings.Settings["UserID"].Value = userid;
                            config.AppSettings.Settings["UserName"].Value = username;
                            //config.AppSettings.Settings["UserPwd"].Value = CkbState.Checked == true ? password : "";
                            //config.AppSettings.Settings["CheckState"].Value = cbUseMes.Checked == true ? "1" : "0";

                            config.Save(ConfigurationSaveMode.Modified);

                            // 强制刷新配置
                            ConfigurationManager.RefreshSection("appSettings");

                            //调用封装的写入日志方法
                            PageDataDto.SystemLogInfoAdd("登录", "进行了系统登录");


                            // 在这里添加登录成功后的逻辑
                            this.Hide(); // 隐藏登录表单
                            Main mainForm = new Main
                            {
                                UserName = username, // 设置Username属性的值
                                UserID = userid
                            };
                            mainForm.Show(); // 显示首页表单
                        }
                        else if (result.RoleCount == 0)
                        {
                            MessageBox.Show("当前登录用户不存在权限菜单，请联系管理员进行添加！", "异常信息 ！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else if (!result.RoleState)
                        {
                            MessageBox.Show("当前登录用户所属角色已失效，请联系管理员启用！", "异常信息 ！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else if (!result.State)
                        {
                            TbxUser.Text = "";
                            TbxPwd.Text = "";
                            TbxUser.Focus();
                            MessageBox.Show("当前登录用户已被禁用，请联系管理员进行启用！", "异常信息 ！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    else
                    {
                        TbxUser.Text = "";
                        TbxPwd.Text = "";
                        TbxUser.Focus();
                        MessageBox.Show("请重新输入账号和密码！", "账号或密码输入错误 ！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("服务器连接失败，请检查网络！", "网络通讯异常 ！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            else
            {
                MessageBox.Show("请重新输入账号和密码！", "账号或密码不能为空 ！", MessageBoxButtons.OK, MessageBoxIcon.Error);

                TbxUser.Focus();
                if (!string.IsNullOrWhiteSpace(username))
                {
                    TbxPwd.Focus();
                }
            }
        }

        private void SignIn_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 写入配置
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["IsMesUserLogin"].Value = "0";
            config.AppSettings.Settings["IsLocalUserLogin"].Value = "0";

            config.Save(ConfigurationSaveMode.Modified);

            // 强制刷新配置
            ConfigurationManager.RefreshSection("appSettings");

            e.Cancel = true;

            // 关闭当前页面
            this.Hide();

            // 终止整个应用程序的运行
            Environment.Exit(Environment.ExitCode);
        }

        private void TbxUser_KeyPress(object sender, KeyPressEventArgs e)
        {
            //if (e.KeyChar >= '0' && e.KeyChar <= '9' || Char.IsLetter(e.KeyChar))//输入1-8位数字或字母
            //{
            //    if (TbxUser.Text.Length <= 11)
            //    {
            //        e.Handled = false;
            //    }
            //    else if (TbxUser.SelectionLength > 1)
            //    {
            //        e.Handled = false;//选择多个
            //    }
            //    else
            //    {
            //        e.Handled = true;
            //    }
            //}

            ////e.KeyChar == '.' ||
            //else if (e.KeyChar == (char)Keys.Return) //Tab或回车键
            //{
            //    e.Handled = true;
            //    SendKeys.Send("{TAB}");
            //}
            //else if (e.KeyChar == '\b' || (int)e.KeyChar == 7)
            //    e.Handled = false;//删除
            //else
            //    e.Handled = true;
        }

        private void TbxPwd_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar >= '0' && e.KeyChar <= '9' || Char.IsLetter(e.KeyChar) || Char.IsPunctuation(e.KeyChar))//输入1-8位数字或字母
            {
                if (TbxPwd.Text.Length <= 15)
                {
                    e.Handled = false;
                }
                else if (TbxPwd.SelectionLength > 1)
                {
                    e.Handled = false;//选择多个
                }
                else
                {
                    e.Handled = true;
                }
            }
            else if (e.KeyChar == (char)Keys.Return) //Tab或回车键
            {
                e.Handled = true;
                SendKeys.Send("{TAB}");
            }
            else if (e.KeyChar == '\b' || (int)e.KeyChar == 7)
                e.Handled = false;//删除
            else
                e.Handled = true;
        }

        private void panel1_Click(object sender, EventArgs e)
        {
            this.pMESst.Visible = true;
        }

        private void panel3_Click(object sender, EventArgs e)
        {
            this.pMESst.Visible = false;
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            string[] arrString = tbWorkStation.Text.Split('-');
            if (arrString.Length < 3 || (arrString.Length == 3 && string.IsNullOrWhiteSpace(arrString[2])))
            {
                MessageBox.Show("工站信息格式错误，请输入正确的工站信息。", "系统提示", MessageBoxButtons.OK);
                return;
            }

            //二次确认提示 add by zxm
            var line = tbLine.Text.Split('-')[2];
            if(!int.TryParse(arrString[2].Substring(arrString[2].Length - 2),out int workSeq))
            {
                MessageBox.Show("工站信息末尾工序必须是数字", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            DialogResult dlgResult = MessageBox.Show($"您确认修改本机产线为【{line}】、工序号【{workSeq}】？", "确认修改", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlgResult == DialogResult.Yes)
            {
                //var gongXuNum = int.Parse(tbZiYuanNo.Text.Trim().Substring(tbZiYuanNo.Text.Trim().Length - 2)); 
                //更新MES设置
                BLL.Bll.UpdateMesSet(tbMesIP.Text.Trim(), tbMesPort.Text.Trim(), tbLine.Text.Trim(),
                    tbWorkStation.Text.Trim(), tbZiYuanNo.Text.Trim(), workSeq.ToString());

                // 写入配置
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.Save(ConfigurationSaveMode.Modified);

                // 强制刷新配置
                ConfigurationManager.RefreshSection("appSettings");
                MessageBox.Show("参数设置成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                //取消选择，则撤销修改
            }
        }

        string PassworkKey = "BYD14SYB";//加密密钥

        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string Decrypt(string str)
        {
            byte[] temp = StringToarrByte(str);
            byte[] _password = ASCIIEncoding.Default.GetBytes(PassworkKey);

            byte[] result = new byte[temp.Length];
            int a = 0;
            for (int i = 0; i < temp.Length; i++)
            {
                byte b = _password[a];
                a++;
                if (a >= PassworkKey.Length)
                {
                    a = 0;
                }

                byte c = temp[i];
                result[i] += (byte)(c ^ b);
            }
            return ASCIIEncoding.Default.GetString(result).Trim();
        }

        /// <summary>
        /// 将字符串转为二进制数组
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private byte[] StringToarrByte(string str)
        {
            byte[] result = new byte[str.Length / 2];
            for (int i = 0; i < str.Length; i += 2)
            {
                string temp = str.Substring(i, 2);
                result[i / 2] = (byte)hexToChar(temp);
            }
            return result;
        }

        /// <summary>
        /// 16进制转字符
        /// </summary>
        /// <param name="strHex"></param>
        /// <returns></returns>
        private byte hexToChar(string strHex)
        {
            return (byte)Int32.Parse(strHex, System.Globalization.NumberStyles.HexNumber);
        }

        /// <summary>
        /// 离开，失去焦点判定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TbxUser_Leave(object sender, EventArgs e)
        {
            if (this.TbxUser.Text.Trim().ToLower() == "admin")
            {
                this.cbUseMes.Checked = false;//不勾选MES
            }
            else
            {
                this.cbUseMes.Checked = true;
            }
        }
    }
}
